# 设置MySQL连接参数
$mysqlHost = "localhost"
$mysqlUser = "root"
$mysqlPassword = "root"
$mysqlDatabase = "ry-vue"

# 音频文件目录
$audioDir = "./word-audio"

# 错误处理函数
function Write-ErrorLog {
    param([string]$message)
    Write-Host "错误: $message" -ForegroundColor Red
}

# 添加进度显示函数
function Write-Progress {
    param([string]$message)
    Write-Host $message -ForegroundColor Cyan
}

try {
    Write-Progress "正在初始化导入程序..."
    
    # 检查MySQL命令是否可用
    Write-Progress "检查MySQL环境..."
    if (-not (Get-Command mysql -ErrorAction SilentlyContinue)) {
        throw "未找到MySQL命令，请确保MySQL已安装且已添加到系统环境变量中"
    }
    Write-Progress "MySQL环境检查通过"

    # 检查音频目录是否存在
    Write-Progress "检查音频文件目录..."
    if (-not (Test-Path $audioDir)) {
        throw "音频文件目录 '$audioDir' 不存在"
    }
    Write-Progress "音频文件目录检查通过"

    # 获取所有MP3文件
    Write-Progress "扫描MP3文件..."
    $audioFiles = Get-ChildItem -Path $audioDir -Filter *.mp3
    if ($audioFiles.Count -eq 0) {
        throw "未找到任何MP3文件"
    }

    Write-Host "\n开始导入音频文件..." -ForegroundColor Green
    Write-Host "找到 $($audioFiles.Count) 个MP3文件" -ForegroundColor Green
    Write-Host "按任意键开始导入，或按Ctrl+C取消..." -ForegroundColor Yellow
    $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

    $processedCount = 0
    foreach ($file in $audioFiles) {
        try {
            # 获取文件名（不含扩展名）作为单词
            $word = [System.IO.Path]::GetFileNameWithoutExtension($file.Name)
            Write-Host "\n正在处理: $word ($($processedCount + 1)/$($audioFiles.Count))" -ForegroundColor Cyan
            
            # 读取音频文件内容为二进制
            Write-Progress "读取音频文件..."
            $audioContent = [System.IO.File]::ReadAllBytes($file.FullName)
            
            # 将二进制内容转换为Base64字符串
            Write-Progress "转换音频数据..."
            $base64Audio = [System.Convert]::ToBase64String($audioContent)
            
            # 构造SQL语句，使用参数化查询避免SQL注入
            Write-Progress "准备SQL语句..."
            $sql = @"
INSERT INTO sys_word_audio (word, audio_content) 
VALUES ('$($word -replace "'", "''")','$base64Audio') 
ON DUPLICATE KEY UPDATE audio_content = VALUES(audio_content);
"@
            
            # 将SQL语句写入临时文件
            $sql | Out-File -FilePath "temp.sql" -Encoding UTF8 -NoNewline
            
            # 执行MySQL命令
            Write-Progress "执行数据库操作..."
            $mysqlCmd = "mysql -h `"$mysqlHost`" -u `"$mysqlUser`" -p`"$mysqlPassword`" `"$mysqlDatabase`" < temp.sql"
            $mysqlResult = Invoke-Expression $mysqlCmd 2>&1
            if ($LASTEXITCODE -ne 0) {
                throw "MySQL执行失败: $mysqlResult"
            }
            
            $processedCount++
            Write-Host "成功导入音频: $word" -ForegroundColor Green
        }
        catch {
            Write-ErrorLog "处理文件 $($file.Name) 时出错: $_"
            Write-Host "按任意键继续处理下一个文件，或按Ctrl+C退出..." -ForegroundColor Yellow
            $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
        }
    }

    # 清理临时文件
    if (Test-Path "temp.sql") {
        Remove-Item -Path "temp.sql"
    }

    Write-Host "\n音频导入完成！" -ForegroundColor Green
    Write-Host "成功处理: $processedCount/$($audioFiles.Count) 个文件" -ForegroundColor Green
}
catch {
    Write-ErrorLog $_.Exception.Message
}
finally {
    Write-Host "\n按任意键退出..." -ForegroundColor Yellow
    $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}